package com.moyun.zbmy.zizhou.ui.activities;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Pair;
import android.view.View;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.jiongbull.jlog.JLog;
import com.moyun.zbmy.zizhou.R;
import com.moyun.zbmy.zizhou.application.Constances;
import com.moyun.zbmy.zizhou.base.BaseActivity;
import com.moyun.zbmy.zizhou.beans.FocusColumn;
import com.moyun.zbmy.zizhou.beans.NewsDate;
import com.moyun.zbmy.zizhou.beans.NewsItem;
import com.moyun.zbmy.zizhou.http.AbsListNetCallback;
import com.moyun.zbmy.zizhou.http.NetUtils;
import com.moyun.zbmy.zizhou.ui.adapter.NewsListAdapter;
import com.moyun.zbmy.zizhou.ui.adapter.ThirdCountryAdapter;
import com.moyun.zbmy.zizhou.ui.adapter.holder.News24Holder;
import com.moyun.zbmy.zizhou.ui.fragment.HomeFragment;
import com.moyun.zbmy.zizhou.ui.util.IListShowData;
import com.moyun.zbmy.zizhou.ui.utils.MutilDateNewsGetHelper;
import com.moyun.zbmy.zizhou.ui.utils.TitleUtils;
import com.moyun.zbmy.zizhou.ui.utils.UIUtils;
import com.moyun.zbmy.zizhou.utils.ListTypeUtils;
import com.ruihang.generalibrary.utils.DateUtils;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.UrlUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 第三方区县新闻列表
 */
public class ThirdCountryNewsActivity extends BaseActivity implements View.OnClickListener, CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener, News24Holder.ItemClickListener {
    public static final String DATA_URL = "data_url";
    public static final String DATA_TITLE = "data_title";
    public static final String DATA_DOMAIN = "data_domain";
    @BindView(R.id.news_list_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView recyclerView;
    private ThirdCountryAdapter adapter;
    private MutilDateNewsGetHelper hour24GetHelper;

    private String dataTitle;
    private String dataUrl;
    private String dataDomain;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dataUrl = getIntent().getStringExtra(DATA_URL);
        dataTitle = getIntent().getStringExtra(DATA_TITLE);
        dataDomain = getIntent().getStringExtra(DATA_DOMAIN);
        new TitleUtils(this).setBackClickListener(this);
        initView();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_third_country_list);
        ButterKnife.bind(this);
    }

    private void initView() {
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);

        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        refreshLayout.setLoadMoreEnabled(false);
        refreshLayout.autoRefresh();
    }


    @Override
    public void onRefresh() {
        getNews24Date();
    }

    @Override
    public void onLoadMore() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.loadMoreComplete();
        } else {
            getNews24Page(false);
        }
    }


    /**
     * 首次请求、下拉刷新加载数据
     *
     * @return
     */
    private boolean getNews24Date() {
        if (TextUtils.isEmpty(dataUrl) || TextUtils.isEmpty(dataDomain)) {

            return false;
        }
        NetUtils.getNetAdapter().getNewsDateArray(getOwnerName(), UrlUtils.linkUrls(dataDomain, dataUrl), new AbsListNetCallback<NewsDate>(ListTypeUtils.NewsItem()) {
            boolean b = true;

            @Override
            public void onSuc(List<NewsDate> newsItems) {
                if (ListUtils.isListValued(newsItems)) {
                    for (int i = 0; i < newsItems.size(); i++) {
                        newsItems.get(i).setNewsListUrl(UrlUtils.linkUrls(dataDomain, newsItems.get(i).getNewsListUrl()));
                    }
                    init24Helper().setDates(newsItems);
                    b = !getNews24Page(true);
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
            }

            @Override
            public void onEnd() {
                super.onEnd();
                if (b) {
                    refreshLayout.refreshComplete();
                }
            }
        });
        return true;
    }

    /**
     * 加载更多数据
     *
     * @param reset
     * @return
     */
    private boolean getNews24Page(final boolean reset) {
        if (!init24Helper().hasValuedDate()) {
            if (reset) {
                if (adapter != null) {
                    adapter.clean();
                }
            }
            return false;
        }
        hour24GetHelper.getNewsList(20, reset
                , new AbsListNetCallback<IListShowData>(IListShowData.class) {

                    @Override
                    public void onSuc(List<IListShowData> newsItems) {
                        for (int i = 0; i < newsItems.size(); i++) {
                            IListShowData t = newsItems.get(i);
                            if (t instanceof NewsItem) {
                                ((NewsItem) newsItems.get(i)).setNewsImage(UrlUtils.linkUrls(dataDomain, ((NewsItem) newsItems.get(i)).getNewsImage()));
                                ((NewsItem) newsItems.get(i)).setNewsUrl(UrlUtils.linkUrls(dataDomain, ((NewsItem) newsItems.get(i)).getNewsUrl()));
                            }
                        }
                        setData(newsItems, reset);
                    }

                    @Override
                    public void onEnd() {
                        super.onEnd();
                        if (reset) {
                            refreshLayout.refreshComplete();
                        } else {
                            refreshLayout.loadMoreComplete();
                        }
                        boolean b = !hour24GetHelper.hasGetAll();
                        refreshLayout.setLoadMoreEnabled(b);
                    }
                });
        return true;
    }

    private void setData(List<IListShowData> list, boolean reset) {
        if (ListUtils.isListValued(list)) {
            if (adapter == null) {
                adapter = new ThirdCountryAdapter(this, list, this);
                ArrayList<Pair<String, String>> pairs = new ArrayList<>();
                pairs.add(new Pair<>("页面", "首页"));
                pairs.add(new Pair<>("栏目", "时讯"));
                adapter.setActivity(this);
                adapter.setPairs(pairs);
                recyclerView.setAdapter(adapter);
            } else {
                if (reset) {
                    adapter.setData(list);
                } else {
                    int pos = adapter.getItemCount();
                    adapter.addDatas(list);
                    if (pos > 0) {
                        adapter.notifyItemChanged(pos - 1);
                    }
                }
            }
        } else {
            if (reset) {
                if (adapter != null) {
                    adapter.clean();
                }
            }
        }
    }

    @Override
    public void onDestroy() {
        if (refreshLayout != null) {
            refreshLayout.setOnRefreshListener(null);
            refreshLayout.setOnLoadMoreListener(null);
        }
        super.onDestroy();
    }


    private MutilDateNewsGetHelper init24Helper() {
        if (hour24GetHelper == null) {
            hour24GetHelper = new MutilDateNewsGetHelper(this);
            hour24GetHelper.setShouldSetTitleAfter(true);
        }
        return hour24GetHelper;
    }


    @Override
    public void ItemOnClick(NewsItem item) {
        HashMap<String, String> map = new HashMap<>();
        map.put("区县圈", "详情");
        Intent intent = new Intent(this, CountyNewsDetailActivity.class);
        intent.putExtra(BaseActivity.EX_URL, item.getNewsUrl());
        intent.putExtra("TAG", map);
        intent.putExtra(CountyNewsDetailActivity.EX_BASE_NEWS_DOMAIN, dataDomain);
        intent.putExtra(Constances.IS_CITY_STATE, true);
        startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_top_edit:
                onBackPressed();
                break;
            case R.id.title_top_back:
                onBackPressed();
                break;
        }
    }
}
